package com.liankuan.console.service.ServiceImpl;

import com.liankuan.console.controller.vo.StrategyListVO;
import com.liankuan.console.dto.Strategy;
import com.liankuan.console.dto.UserStrategy;
import com.liankuan.console.repository.StrategyRepository;
import com.liankuan.console.repository.UserStrategyRepository;
import com.liankuan.console.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserStrategyServiceImpl {
    private final UserStrategyRepository userStrategyRepository;
    private final StrategyRepository strategyRepository;
    private final Config config;

    @Autowired
    public UserStrategyServiceImpl(UserStrategyRepository userStrategyRepository, StrategyRepository
            strategyRepository, Config config) {
        this.userStrategyRepository = userStrategyRepository;
        this.strategyRepository = strategyRepository;
        this.config = config;
    }


    /**
     * 获取用户对应的所有的策略
     *
     * @param userId
     * @return
     */
    public List<StrategyListVO> findAllByUserId(int userId) {
        List<UserStrategy> userStrategies = userStrategyRepository.findAllByUserId(userId);
        if (userStrategies.isEmpty()) {
            return Collections.emptyList();
        }
        return userStrategies.stream().map(record -> {
            Strategy strategy = strategyRepository.findOne(record.getStrategyId());
            StrategyListVO strategyListVO = new StrategyListVO(strategy);
            strategyListVO.setLevel(record.getLevel());

            return strategyListVO;
        }).collect(Collectors.toList());
    }

    /**
     * 策略创建者创建一条策略
     *
     * @param strategy
     * @param userId
     */
    public void createUserStrategy(Strategy strategy, int userId) {
        UserStrategy userStrategy = new UserStrategy();
        userStrategy.setStrategyId(strategy.getId());
        userStrategy.setUserId(userId);

        // TODO 默认级别为创建者所有权
        userStrategy.setLevel(config.getCreate());

        userStrategyRepository.save(userStrategy);
    }
}
